<template>
  <view class="water-chart">
    <view class="chart-title flex items-center">
      <image src="/static/images/index-water.png" class="index-water-img">
      </image>
      今日用水
    </view>
    <view class="flex items-center header-ope">
      <text class="hd-num">{{ waterToday | toFixed }}</text>
      <view class="ope-change">
        <text
          :class="['ope-item', curDay === 1 ? 'ope-item-active' : '']"
          @click="curDay = 1"
          >当日</text
        >
        <text
          :class="['ope-item', curDay === 7 ? 'ope-item-active' : '']"
          @click="curDay = 7"
          >累计</text
        >
      </view>
    </view>
    <view class="qiun-charts">
      <canvas canvas-id="canvasArea" id="canvasArea" class="charts"></canvas>
    </view>
  </view>
</template>

<script>
import uCharts from "@/components/u-charts/u-charts.js";
import moment from "moment";
import { mapGetters, mapState } from "vuex";
var _self;
var canvaArea = null;

export default {
  data() {
    return {
      cWidth: "",
      cHeight: "",
      pixelRatio: 1,
      curDay: 1,
      waterTotal: 0,
    };
  },
  filters: {
    toFixed(val, l = 0) {
      return val.toFixed(l)
    }
  },
  computed: {
    ...mapGetters({
      project: "project",
    }),
    ...mapState({
      waterToday: state => state.project.today.water
    }),
    isHour() {
      return this.curDay === 1;
    },
  },
  watch: {
    curDay() {
      this.getServerData();
    },
    project: {
      deep: true,
      handler() {
        this.getServerData();
      },
    },
  },
  mounted() {
    _self = this;
    this.cWidth = uni.upx2px(638);
    this.cHeight = uni.upx2px(260);
    // this.getServerData();
  },
  methods: {
    async getServerData() {
      let url = `/api/energy/consumption/trend/line/${
        this.curDay === 1 ? "hour" : "day"
      }`;
      let data = {
        projectId: this.project.id,
        startDate: moment()
          .subtract(this.curDay, "day")
          .format("YYYY-MM-DD HH:mm:ss"),
        endDate: moment().format("YYYY-MM-DD HH:mm:ss"),
      }
      if (this.curDay === 1) { // 当日的查12小时前的数据，24小时太多了
        data.startDate = moment()
          .subtract(8, "hour")
          .format("YYYY-MM-DD HH:mm:ss")
      }
      const { result } = await this.$request(url, data, "POST");
      const { waterDataMap = {} } = result || {};
      const sortByDate = (a, b) => Date.parse(a) - Date.parse(b);
      const cateSeriesData = {
        categories: [],
        series: [{ data: [], color: "#0AC7B9" }],
      };
      this.waterTotal = 0;
      Object.keys(waterDataMap || {})
        .sort(sortByDate)
        .forEach((date) => {
          cateSeriesData.categories.push(
            moment(date).format(this.isHour ? "HH:mm" : "M.D")
          );
          cateSeriesData.series[0].data.push(
            (waterDataMap[date] || 0).toFixed(2)
          );
          this.waterTotal += Number((waterDataMap[date] || 0).toFixed(2));
        });
      this.waterTotal = Number(this.waterTotal.toFixed(2));
      this.showArea(cateSeriesData);
    },
    showArea(chartData, canvasId = "canvasArea") {
      canvaArea = new uCharts({
        $this: _self,
        canvasId: canvasId,
        type: "area",
        fontSize: 11,
        legend: false,
        dataLabel: false,
        dataPointShape: false,
        background: "#FFFFFF",
        pixelRatio: _self.pixelRatio,
        categories: chartData.categories,
        series: chartData.series,
        // categories: ["2012", "2013", "2014", "2015", "2016", "2017"],
        // series: [{
        // "data": [15, 20, 45, 37, 43, 34],
        // "color" : "#0AC7B9"
        // }],
        animation: true,
        xAxis: {
          disableGrid: true,
          // type:'grid',
          // gridColor:'#CCCCCC',
          // gridType:'dash',
          // dashLength:8
        },
        yAxis: {
          disableGrid: true,
          // gridType:'dash',
          // gridColor:'#CCCCCC',
          // dashLength:8,
          // splitNumber:5,
          // min:10,
          // max:180,
        },
        width: _self.cWidth * _self.pixelRatio,
        height: _self.cHeight * _self.pixelRatio,
        extra: {
          area: {
            type: "curve",
            opacity: 0.2,
            addLine: true,
            width: 2,
            gradient: true,
          },
        },
      });
    },
    // touchArea(e) {
    // 	canvaArea.showToolTip(e, {
    // 		format: function (item, category) {
    // 			return category + ' ' + item.name + ':' + item.data
    // 		}
    // 	});
    // }
  },
};
</script>

<style lang="scss" scoped>
.water-chart {
  padding: 24rpx;
  background-color: #ffffff;
  box-shadow: 0px 3px 14px rgba(209, 209, 209, 0.16);
  .chart-title {
    font-size: 32rpx;
    font-weight: bold;
    .index-water-img {
      width: 40rpx;
      height: 40rpx;
      margin-right: 16rpx;
    }
  }
  .header-ope {
    justify-content: space-between;
    line-height: 59rpx;
    margin-top: 16rpx;
    .hd-num {
      color: $uni-theme-color;
      font-size: 42rpx;
      font-weight: 800;
    }
    .ope-change {
      border-radius: 6rpx;
      line-height: 36rpx;
      font-size: 22rpx;
      font-weight: 500;
      border: 1px solid $uni-theme-color;
      .ope-item {
        display: inline-block;
        width: 74rpx;
        text-align: center;
        color: $uni-theme-color;
      }
      .ope-item-active {
        color: #ffffff;
        background-color: $uni-theme-color;
      }
    }
  }
}
/*样式的width和height一定要与定义的cWidth和cHeight相对应*/
.qiun-charts {
  width: 638rpx;
  height: 260rpx;
  background-color: #ffffff;
}

.charts {
  width: 638rpx;
  height: 260rpx;
  background-color: #ffffff;
}
</style>
